<?php
namespace common\models\recharge;

use common\models\Common;
use common\models\Status;
use common\models\user\User;
use yii\base\Exception;

/**
 * Created by PhpStorm.
 * Time: 4:12 PM
 */
class RechargeGgh extends Common
{
    public static function tableName()
    {
        return '{{%recharge_ggh_order}}';
    }

    //用户
    public function getUser() {
        return $this->hasOne(User::className(), ['id' => 'user_id']);
    }


    /**
     * 生成订单编号
     * @return string
     */
    public function _createOrderNumber() {
        do {
            $orderNumber = "RE" . date('ymdH') . mt_rand(1000, 9999);
            $where['order_number'] = $orderNumber;
            $exist = static::getCountByWhere($where);
        } while($exist > 0);

        return $orderNumber;
    }

    /**
     * 确认收货
     * @param int $orderId
     * @return bool|string
     * @throws \yii\db\Exception
     */
    public function finished($orderId = 0) {
        $trans = \Yii::$app->db->beginTransaction();
        try {
            #完成订单
            $oData['status'] = Status::GOODS_ORDER_SHOUHUO;
            $oData['finish_time'] = date("Y-m-d H:i:s");
            $res = static::updateData($oData, ['id' => $orderId]);
            if ($res === false) {
                throw new Exception("系统错误");
            }

            $trans->commit();
            return true;
        } catch (Exception $e) {
            $trans->rollBack();
            return $e->getMessage();
        }

    }
}
